<template>
  <div style="height: 100%">
    <a-spin :spinning="loading" wrapperClassName="spinning-container">
      <page-header :title="l('Settings')"></page-header>
      <a-card :bordered="false">
        <a-tabs v-if="hostSettings">
          <!-- 基本信息 -->
          <a-tab-pane :tab="l('General')" key="1" v-if="showTimezoneSelection">
            <a-form :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
              <a-form-item :label="l('Timezone')">
                <timezone-combo
                  :selectedTimeZone="hostSettings.general.timezone"
                  :defaultTimezoneScope="defaultTimezoneScope"
                  @selectedTimeZoneChange="selectedTimeZoneChange"
                ></timezone-combo>
              </a-form-item>
            </a-form>
          </a-tab-pane>
          <!-- 租户管理设置 -->
          <a-tab-pane :tab="l('TenantManagement')" key="2" v-if="hostSettings.tenantManagement">
            <section>
              <h3>{{ l('FormBasedRegistration') }}</h3>
              <!-- 允许租户注册到系统 -->
              <a-checkbox v-model:checked="hostSettings.tenantManagement.allowSelfRegistration">
                {{ l('AllowTenantsToRegisterThemselves') }}
              </a-checkbox>
              <p class="text-grey-dark">{{ l('AllowTenantsToRegisterThemselves_Hint') }}</p>
              <br />
              <!-- 新注册租户默认激活 -->
              <a-checkbox
                v-model:checked="hostSettings.tenantManagement.isNewRegisteredTenantActiveByDefault"
                v-if="hostSettings.tenantManagement.allowSelfRegistration"
              >
                {{ l('NewRegisteredTenantsIsActiveByDefault') }}
              </a-checkbox>
              <p v-if="hostSettings.tenantManagement.allowSelfRegistration" class="text-grey-dark">
                {{ l('NewRegisteredTenantsIsActiveByDefault_Hint') }}
              </p>
              <br />
              <!-- 租户注册时使用图片验证码(captcha) -->
              <a-checkbox
                v-model:checked="hostSettings.tenantManagement.useCaptchaOnTenantRegistration"
                v-if="hostSettings.tenantManagement.allowSelfRegistration"
              >
                {{ l('UseCaptchaOnTenantRegistration') }}
              </a-checkbox>

              <!-- 租户注册图片验证码类型 -->
              <div
                v-if="
                  hostSettings.tenantManagement.useCaptchaOnTenantRegistration &&
                  hostSettings.tenantManagement.allowSelfRegistration
                "
              >
                <p>
                  <br />
                </p>
                <p>
                  <label class="requiredlabel"> * </label>
                  {{ l('CaptchaOnTenantRegistrationType') }}:
                </p>
                <a-select
                  style="width: 100%"
                  v-model:value="hostSettings.tenantManagement.configCaptchaOnTenantType"
                  @change="CaptchaOnTenantRegistrationTypeChange"
                  :placeholder="l('CaptchaOnHostUserLoginType')"
                >
                  <a-select-option value="Number">纯数字</a-select-option>
                  <a-select-option value="English">纯字母</a-select-option>
                  <a-select-option value="NumberAndLetter">数值与字母的组合</a-select-option>
                </a-select>
                <p>
                  <br />
                </p>
              </div>
              <!-- 租户注册图片验证码长度  -->
              <div
                v-if="
                  hostSettings.tenantManagement.useCaptchaOnTenantRegistration &&
                  hostSettings.tenantManagement.allowSelfRegistration
                "
              >
                <p>
                  <label class="requiredlabel">*</label>
                  {{ l('CaptchaOnTenantRegistrationLength') }}:
                </p>
                <a-input-number
                  id="inputNumber"
                  :min="4"
                  :max="10"
                  :step="1"
                  v-model:value="hostSettings.tenantManagement.configCaptchaOnTenantLength"
                />
                <p><br /> </p>
              </div>
              <!-- 版本  -->
              <p>{{ l('Edition') }}:</p>
              <a-select
                style="width: 100%"
                v-model:value="hostSettings.tenantManagement.defaultEditionId"
                @change="versionHandleChange"
                :placeholder="l('Edition')"
              >
                <a-select-option v-for="item in versionList" :value="item.value" :key="item.value">
                  {{ item.displayText }}
                </a-select-option>
              </a-select>
            </section>
          </a-tab-pane>
          <!-- 用户管理 -->
          <a-tab-pane :tab="l('UserManagement')" key="3" v-if="hostSettings.userManagement">
            <h3>{{ l('FormBasedRegistration') }}</h3>
            <!-- 允许用户注册 -->
            <a-checkbox v-model:checked="hostSettings.userManagement.allowSelfRegistrationUser">
              {{ l('AllowUsersToRegisterThemselves') }}
            </a-checkbox>
            <span class="text-sm text-grey-dark">
              &nbsp;&nbsp;{{ l('AllowUsersToRegisterThemselves_Hint') }}
            </span>
            <p></p>
            <!-- 注册用户默认激活 -->
            <a-checkbox
              v-model:checked="hostSettings.userManagement.isNewRegisteredUserActiveByDefault"
            >
              {{ l('NewRegisteredUsersIsActiveByDefault') }}
            </a-checkbox>
            <span class="text-sm text-grey-dark">
              &nbsp;&nbsp;{{ l('NewRegisteredUsersIsActiveByDefault_Hint') }}
            </span>
            <p></p>
            <!-- 必须验证邮箱地址后才能登录 -->
            <a-checkbox
              v-model:checked="hostSettings.userManagement.isEmailConfirmationRequiredForLogin"
              >{{ l('EmailConfirmationRequiredForLogin') }}</a-checkbox
            >
            <p></p>
            <!-- 配置验证码 -->
            <h3>{{ l('ConfigCaptchaRules') }}</h3>
            <!--用户登录使用验证码-->
            <a-checkbox
              v-model:checked="hostSettings.userManagement.captchaConfig.useCaptchaOnUserLogin"
            >
              {{ l('UseCaptchaOnUserLogin') }}
            </a-checkbox>
            <p></p>
            <!--忘记密码使用验证码-->
            <a-checkbox
              v-model:checked="
                hostSettings.userManagement.captchaConfig.useCaptchaOnUserForgotPassword
              "
            >
              {{ l('UseCaptchaOnUserForgotPassword') }}
            </a-checkbox>
            <p></p>
            <!-- 用户注册使用验证码-->
            <a-checkbox
              v-model:checked="
                hostSettings.userManagement.captchaConfig.useCaptchaOnUserRegistration
              "
            >
              {{ l('UseCaptchaOnUserRegistration') }}
            </a-checkbox>
            <p></p>
            <!-- 宿主用户登陆图片验证码类型   -->
            <div
              v-if="
                hostSettings.userManagement.captchaConfig.useCaptchaOnUserLogin ||
                hostSettings.userManagement.captchaConfig.useCaptchaOnUserRegistration ||
                hostSettings.userManagement.captchaConfig.useCaptchaOnUserForgotPassword
              "
            >
              <!--验证码类型-->
              <p><label class="requiredlabel">*</label>{{ l('ConfigCaptchaType') }}:</p>
              <a-select
                style="width: 100%"
                v-model:value="hostSettings.userManagement.captchaConfig.configCaptchaOnUserType"
                @change="useCaptchaOnUserLoginHandleChange"
                :placeholder="l('CaptchaOnHostUserLoginType')"
              >
                <a-select-option value="Number">纯数字</a-select-option>
                <a-select-option value="English">纯字母</a-select-option>
                <a-select-option value="NumberAndLetter">数值与字母的组合</a-select-option>
              </a-select>
              <p>
                <br />
              </p>
            </div>
            <!-- 验证码长度 -->
            <div
              v-if="
                hostSettings.userManagement.captchaConfig.useCaptchaOnUserLogin ||
                hostSettings.userManagement.captchaConfig.useCaptchaOnUserRegistration ||
                hostSettings.userManagement.captchaConfig.useCaptchaOnUserForgotPassword
              "
            >
              <p><label class="requiredlabel">*</label>{{ l('ConfigCaptchaLength') }}:</p>
              <a-input-number
                id="inputNumber"
                :min="4"
                :max="10"
                :step="1"
                v-model:value="hostSettings.userManagement.captchaConfig.configCaptchaOnUserLength"
              />
              <p>
                <br />
              </p>
            </div>
          </a-tab-pane>
          <!-- 安全 -->
          <a-tab-pane :tab="l('Security')" key="4" v-if="hostSettings.security">
            <!--是否强制修改密码-->
            <h3>{{ l('WhetherToForceAPasswordChange') }}</h3>
            <a-row>
              <a-switch
                v-model:checked="hostSettings.security.updatePasswordForceEditDto.switchStatus"
                name="updatePasswdForceInput"
              >
              </a-switch>
            </a-row>
            <p></p>
            <!-- 有效时长 -->
            <a-row v-if="hostSettings.security.updatePasswordForceEditDto.switchStatus">
              <label class="requiredlabel">*</label>{{ l('ValidDuration') }}&nbsp;&nbsp;
              <a-input-number
                name="effectiveTime"
                v-model:value="hostSettings.security.updatePasswordForceEditDto.effectiveTimeLast"
                :min="1"
                :step="1"
                precision="cut"
              ></a-input-number>
              <!-- 单位 -->
              {{ l('Unit') }}
              <g-enum
                :type="select"
                :value="hostSettings.security.updatePasswordForceEditDto.timeUnitEnum"
                :optionMenu="'TimeUnitEnum'"
                :placeholder="l('Unit')"
                @valueChange="updatePasswordForceChange($event)"
              ></g-enum>
            </a-row>
            <br />
            <hr />
            <!-- 演示模式 -->
            <h3>{{ l('DemoMode') }}</h3>
            <a-row>
              <a-checkbox
                disabled="ture"
                v-model:checked="hostSettings.security.previewMode"
                name="Setting_Security_PreviewMode"
              >
                {{ l('EnablePresentationMode') }}
              </a-checkbox>
            </a-row>
            <!-- 密码复杂性 -->
            <h3>{{ l('PasswordComplexity') }}</h3>
            <!-- 使用默认设置 -->
            <a-checkbox
              v-model:checked="hostSettings.security.useDefaultPasswordComplexitySettings"
            >
              {{ l('UseDefaultSettings') }}
            </a-checkbox>
            <br />
            <!-- 缺少数字 -->
            <a-checkbox
              v-model:checked="hostSettings.security.passwordComplexity.requireDigit"
              :disabled="hostSettings.security.useDefaultPasswordComplexitySettings"
            >
              {{ l('PasswordComplexity_RequireDigit') }}
            </a-checkbox>
            <br />
            <!-- 缺少小写字母 -->
            <a-checkbox
              v-model:checked="hostSettings.security.passwordComplexity.requireLowercase"
              :disabled="hostSettings.security.useDefaultPasswordComplexitySettings"
            >
              {{ l('PasswordComplexity_RequireLowercase') }}
            </a-checkbox>
            <br />
            <!-- 缺少特殊字符 -->
            <a-checkbox
              v-model:checked="hostSettings.security.passwordComplexity.requireNonAlphanumeric"
              :disabled="hostSettings.security.useDefaultPasswordComplexitySettings"
            >
              {{ l('PasswordComplexity_RequireNonAlphanumeric') }}
            </a-checkbox>
            <br />
            <!-- 缺少大写字母 -->
            <a-checkbox
              v-model:checked="hostSettings.security.passwordComplexity.requireUppercase"
              :disabled="hostSettings.security.useDefaultPasswordComplexitySettings"
            >
              {{ l('PasswordComplexity_RequireUppercase') }}
            </a-checkbox>
            <p>
              <label
                v-if="!hostSettings.security.useDefaultPasswordComplexitySettings"
                class="requiredlabel"
              >
                *
              </label>
              {{ l('PasswordComplexity_RequiredLength') }}:
            </p>
            <a-input-number
              id="inputNumber"
              :step="1"
              :min="6"
              v-if="!hostSettings.security.useDefaultPasswordComplexitySettings"
              v-model:value="hostSettings.security.passwordComplexity.requiredLength"
            />
            <a-input-number
              id="inputNumber"
              :step="1"
              disabled
              :min="6"
              v-if="hostSettings.security.useDefaultPasswordComplexitySettings"
              v-model:value="hostSettings.security.defaultPasswordComplexity.requiredLength"
            />
            <p>
              <br />
            </p>
            <!-- 锁定用户 -->
            <h3>{{ l('UserLockOut') }}</h3>

            <!-- 登录失败后启用用户的帐户锁定 -->
            <a-checkbox v-model:checked="hostSettings.security.userLockOut.isEnabled">
              {{ l('EnableUserAccountLockingOnFailedLoginAttemts') }}
            </a-checkbox>
            <p></p>
            <!-- 在锁定帐户之前的累计登录失败的最大数量: -->
            <p v-if="hostSettings.security.userLockOut.isEnabled">
              <label class="requiredlabel"> * </label>
              {{ l('MaxFailedAccessAttemptsBeforeLockout') }}:
            </p>
            <a-input-number
              v-if="hostSettings.security.userLockOut.isEnabled"
              id="inputNumber"
              :step="1"
              :min="5"
              v-model:value="hostSettings.security.userLockOut.maxFailedAccessAttemptsBeforeLockout"
            />
            <!-- 帐户锁定持续时间 -->
            <p v-if="hostSettings.security.userLockOut.isEnabled"></p>
            <p v-if="hostSettings.security.userLockOut.isEnabled">
              <label class="requiredlabel">*</label>
              {{ l('DefaultAccountLockoutDurationAsSeconds') }}:
            </p>
            <a-input-number
              v-if="hostSettings.security.userLockOut.isEnabled"
              id="inputNumber"
              :step="1"
              :min="60"
              v-model:value="hostSettings.security.userLockOut.defaultAccountLockoutSeconds"
            />
            <!-- 两步认证登录 -->
            <p></p>
            <h3 v-if="hostSettings.security.twoFactorLogin.isEnabled">{{ l('TwoFactorLogin') }}</h3>
            <a-checkbox
              v-model:checked="hostSettings.security.twoFactorLogin.isEnabled"
              v-if="hostSettings.security.twoFactorLogin.isEnabled"
            >
              {{ l('EnableTwoFactorLogin') }}
            </a-checkbox>
            <p></p>
            <a-checkbox
              v-model:checked="hostSettings.security.twoFactorLogin.isEmailProviderEnabled"
              v-if="hostSettings.security.twoFactorLogin.isEnabled"
            >
              {{ l('IsEmailVerificationEnabled') }}
            </a-checkbox>
            <p></p>
            <a-checkbox
              v-model:checked="hostSettings.security.twoFactorLogin.isSmsProviderEnabled"
              v-if="hostSettings.security.twoFactorLogin.isEnabled"
            >
              {{ l('IsSmsVerificationEnabled') }}
            </a-checkbox>
            <p></p>
            <a-checkbox
              v-model:checked="hostSettings.security.twoFactorLogin.isGoogleAuthenticatorEnabled"
              v-if="hostSettings.security.twoFactorLogin.isEnabled"
            >
              {{ l('IsGoogleAuthenticatorEnabled') }}
            </a-checkbox>
            <p></p>
            <a-checkbox
              v-model:checked="hostSettings.security.twoFactorLogin.isRememberBrowserEnabled"
              v-if="hostSettings.security.twoFactorLogin.isEnabled"
            >
              {{ l('AllowToRememberBrowserForTwoFactorLogin') }}
            </a-checkbox>
            <p></p>
          </a-tab-pane>
          <!-- 邮箱 -->
          <a-tab-pane
            :tab="l('EmailSmtp')"
            key="5"
            v-if="hostSettings.userManagement"
            forceRender="true"
          >
            <a-form :model="form" ref="formRef" :rules="rules" :layout="'vertical'">
              <!-- 默认发送邮箱地址 -->
              <a-form-item
                has-feedback
                v-bind="formItemLayout"
                :label="l('DefaultFromAddress')"
                name="defaultFromAddress"
              >
                <a-input v-model:value="form.defaultFromAddress" />
              </a-form-item>
              <!-- 默认发送人名字 -->
              <a-form-item
                has-feedback
                v-bind="formItemLayout"
                :label="l('DefaultFromDisplayName')"
                name="defaultFromDisplayName"
              >
                <a-input v-model:value="form.defaultFromDisplayName" />
              </a-form-item>
              <!-- SMTP服务器 -->
              <a-form-item
                v-bind="formItemLayout"
                :label="l('SmtpHost')"
                name="smtpHost"
                has-feedback
              >
                <a-input v-model:value="form.smtpHost" />
              </a-form-item>
              <!-- SMTP端口 -->
              <a-form-item
                v-bind="formItemLayout"
                :label="l('SmtpPort')"
                name="smtpPort"
                has-feedback
              >
                <a-input v-model:value="form.smtpPort" />
              </a-form-item>
              <!-- 使用SSL -->
              <a-form-item v-bind="formItemLayout">
                <a-checkbox v-model:checked="form.smtpEnableSsl">{{ l('UseSsl') }}</a-checkbox>
              </a-form-item>
              <!-- 默认身份验证 -->
              <a-form-item v-bind="formItemLayout">
                <a-checkbox v-model:checked="form.smtpUseDefaultCredentials">
                  {{ l('UseDefaultCredentials') }}
                </a-checkbox>
              </a-form-item>
              <!-- 域名 -->
              <a-form-item
                v-bind="formItemLayout"
                :label="l('DomainName')"
                v-if="!form.smtpUseDefaultCredentials"
                name="smtpDomain"
                has-feedback
              >
                <a-input v-model:value="form.smtpDomain" />
              </a-form-item>
              <!-- 用户名 -->
              <a-form-item
                v-bind="formItemLayout"
                :label="l('UserName')"
                v-if="!form.smtpUseDefaultCredentials"
                name="smtpUserName"
                has-feedback
              >
                <a-input v-model:value="form.smtpUserName" />
              </a-form-item>
              <!-- 密码 -->
              <a-form-item
                v-bind="formItemLayout"
                :label="l('Password')"
                v-if="!form.smtpUseDefaultCredentials"
                name="smtpPassword"
                has-feedback
              >
                <a-input type="password" v-model:value="form.smtpPassword" />
              </a-form-item>
              <!-- 测试邮件设置 -->
              <a-form-item
                v-bind="formItemLayout"
                :label="l('TestEmailSettingsHeader')"
                name="testEmailSettingsHeader"
                has-feedback
              >
                <a-input
                  :placeholder="l('TestEmailSettingsHeader')"
                  v-model:value="form.testEmailSettingsHeader"
                >
                </a-input>
              </a-form-item>
              <!-- 发送测试邮件 -->
              <a-button type="primary" @click="sendTestEmail">
                {{ l('SendTestEmail') }}
              </a-button>
            </a-form>
          </a-tab-pane>
          <!--设置系统地址-->
          <a-tab-pane :tab="l('Settings.Urls')" key="7" v-if="hostSettings.urls" forceRender="true">
            <a-form :model="hostSettings.urls" :rules="rules" :layout="'vertical'">
              <!-- 管理端API访问地址 -->
              <a-form-item
                v-bind="formItemLayout"
                :label="l('AdminApiUrl')"
                name="AdminApiUrl"
                has-feedback
              >
                <a-input
                  v-model:value="hostSettings.urls.adminApiUrl"
                  required
                  minlength="6"
                  maxlength="32"
                />
              </a-form-item>
              <!-- 管理端UI访问地址 -->
              <a-form-item
                v-bind="formItemLayout"
                :label="l('AdminUiUrl')"
                name="adminUiUrl"
                has-feedback
              >
                <a-input
                  v-model:value="hostSettings.urls.adminUiUrl"
                  required
                  minlength="6"
                  maxlength="512"
                />
              </a-form-item>
              <!-- 用户中心 访问地址 -->
              <a-form-item
                v-bind="formItemLayout"
                :label="l('UserCenterUrl')"
                name="userCenterUrl"
                has-feedback
              >
                <a-input
                  v-model:value="hostSettings.urls.userCenterUrl"
                  required
                  minlength="6"
                  maxlength="512"
                />
              </a-form-item>
              <!-- 门户端访问地址 -->
              <a-form-item
                v-bind="formItemLayout"
                :label="l('ProtalUrl')"
                name="protalUrl"
                has-feedback
              >
                <a-input
                  v-model:value="hostSettings.urls.protalUrl"
                  required
                  minlength="6"
                  maxlength="512"
                />
              </a-form-item>
            </a-form>
          </a-tab-pane>
          <!-- 保存全部按钮 -->
          <template #rightExtra>
            <a-button :type="'primary'" @click="handleSubmit">
              <save-outlined />
              <span>{{ l('SaveAll') }}</span>
            </a-button>
          </template>
        </a-tabs>
      </a-card>
    </a-spin>
  </div>
</template>

<script lang="ts">
  import { AppComponentBase } from '/@/shared/component-base';
  import {
    CaptchaConfigSetting,
    CommonLookupServiceProxy,
    HostSettingsServiceProxy,
    SendTestEmailInput,
    SubscribableEditionComboboxItemDto,
    TimeUnitEnum,
    UpdatePasswordForceEditDto,
    ValidateCodeType,
  } from '/@/shared/service-proxies';
  import { SaveOutlined } from '@ant-design/icons-vue';
  import { defineComponent } from 'vue';
  import { TimezoneCombo } from '/@/app/admin-shared';
  import { AppPreBootstrap } from '/@/AppPreBootstrap';
  export default defineComponent({
    mixins: [AppComponentBase],
    name: 'host-settings',
    components: {
      TimezoneCombo,
      SaveOutlined,
    },
    data() {
      return {
        hostSettings: {
          // 时区
          general: {
            timezone: '',
          },
          // 租户管理
          tenantManagement: {
            allowSelfRegistration: true,
            isNewRegisteredTenantActiveByDefault: false,
            useCaptchaOnTenantRegistration: false,
            configCaptchaOnTenantLength: 4,
            configCaptchaOnTenantType: '',
            defaultEditionId: '',
          },
          // 用户管理
          userManagement: {
            allowSelfRegistrationUser: true,
            isNewRegisteredUserActiveByDefault: true,
            isEmailConfirmationRequiredForLogin: false,
            useCaptchaOnUserLogin: true,
            captchaOnUserLoginType: '',
            captchaOnUserLoginLength: 4,
            captchaConfig: new CaptchaConfigSetting(),
          },
          // 安全
          security: {
            useDefaultPasswordComplexitySettings: true,
            passwordComplexity: {
              requireDigit: false,
              requireLowercase: false,
              requireNonAlphanumeric: false,
              requireUppercase: false,
              requiredLength: 6,
            },
            defaultPasswordComplexity: {
              requiredLength: 6,
            },
            userLockOut: {
              isEnabled: true,
              maxFailedAccessAttemptsBeforeLockout: 5,
              defaultAccountLockoutSeconds: 300,
            },
            twoFactorLogin: {
              isEnabled: false,
              isEmailProviderEnabled: true,
              isSmsProviderEnabled: true,
              isGoogleAuthenticatorEnabled: false,
              isRememberBrowserEnabled: true,
            },
            previewMode: false,
            updatePasswordForceEditDto: new UpdatePasswordForceEditDto(),
          },
          //邮箱
          email: {},
          urls: {
            protalUrl: '',
            adminApiUrl: '',
            adminUiUrl: '',
            userCenterUrl: '',
          },
        },
        rules: {
          defaultFromAddress: [
            {
              required: true,
              message: this.l('ThisFieldIsRequired'),
            },
            {
              pattern: '^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(.[a-zA-Z0-9-]+)*.[a-zA-Z0-9]{2,6}$',
              message: this.l('NotEmail'),
              trigger: 'blur',
            },
            {
              max: 128,
              message: this.l('MaxLength', 128),
            },
          ],
          defaultFromDisplayName: [
            {
              required: true,
              message: this.l('ThisFieldIsRequired'),
              trigger: 'blur',
            },
            {
              max: 64,
              message: this.l('MaxLength', 64),
            },
          ],
          smtpHost: [
            {
              required: true,
              message: this.l('ThisFieldIsRequired'),
              trigger: 'blur',
            },
            {
              max: 128,
              message: this.l('MaxLength', 128),
            },
          ],
          smtpPort: [
            {
              required: true,
              message: this.l('ThisFieldIsRequired'),
              trigger: 'blur',
            },
            {
              max: 64,
              message: this.l('MaxLength', 64),
            },
          ],
          smtpUserName: [
            {
              required: true,
              message: this.l('ThisFieldIsRequired'),
              trigger: 'blur',
            },
            {
              max: 128,
              message: this.l('MaxLength', 128),
            },
          ],
          smtpDomain: [
            {
              required: true,
              message: this.l('ThisFieldIsRequired'),
              trigger: 'blur',
            },
            {
              max: 128,
              message: this.l('MaxLength', 128),
            },
          ],
          testEmailSettingsHeader: [
            {
              required: true,
              message: this.l('ThisFieldIsRequired'),
              trigger: 'blur',
            },
            {
              max: 128,
              message: this.l('MaxLength', 128),
            },
          ],
          smtpPassword: [
            {
              required: true,
              message: this.l('ThisFieldIsRequired'),
              trigger: 'blur',
            },
            {
              max: 128,
              message: this.l('MaxLength', 128),
            },
          ],
          adminUiUrl: [
            {
              required: true,
              message: this.l('ThisFieldIsRequired'),
              trigger: 'blur',
            },
            {
              max: 512,
              message: this.l('MaxLength', 512),
            },
            {
              min: 6,
              message: this.l('MinLength', 6),
            },
          ],
        },
        form: {
          defaultFromAddress: '',
          defaultFromDisplayName: '',
          smtpHost: '',
          smtpPort: '',
          smtpDomain: '',
          smtpUserName: '',
          smtpPassword: '',
          testEmailSettingsHeader: '',
          smtpEnableSsl: false,
          smtpUseDefaultCredentials: true,
        },

        // 选择时区
        showTimezoneSelection: abp.clock.provider.supportsMultipleTimezone,
        defaultTimezoneScope: 'Application',
        // 邮箱
        formItemLayout: {
          labelCol: {
            xs: { span: 24 },
            sm: { span: 24 },
          },
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 24 },
          },
        },
        commonLookupServiceProxy: new CommonLookupServiceProxy(),
        hostSettingsServiceProxy: new HostSettingsServiceProxy(),
        setEmailInput: new SendTestEmailInput(),
        // 版本list
        versionList: [] as SubscribableEditionComboboxItemDto[],
        // 图片验证码类型
        imgCodeTypeList: [],
        usingDefaultTimeZone: '',
      };
    },
    mounted() {
      this.loading = true;
      this.getData();
      this.getimgCodeTypeList();
      this.getAllSetting();
      Promise.all([this.getData, this.getimgCodeTypeList, this.getAllSetting])
        .then(() => {
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    methods: {
      /**
       * 获取数据
       */
      getData() {
        this.commonLookupServiceProxy
          .getEditionsForCombobox(false)
          .finally(() => {})
          .then((res) => {
            this.versionList = res.items as any;
          });
      },
      /**
       * 获取图片验证嘛类型
       */
      getimgCodeTypeList() {
        this.commonLookupServiceProxy
          .getValidateCodeTypesForCombobox()
          .finally(() => {})
          .then((res) => {
            (this.imgCodeTypeList as any) = res.items;
          });
      },
      /**
       * 获取所有设置
       */
      getAllSetting() {
        this.hostSettingsServiceProxy
          .getAllSettings()
          .finally(() => {})
          .then((res) => {
            (this.hostSettings as any) = res;
            this.$nextTick(() => {
              this.form.defaultFromAddress = String(res.email.defaultFromAddress);
              this.form.defaultFromDisplayName = String(res.email.defaultFromDisplayName);
              this.form.smtpHost = String(res.email.smtpHost);
              this.form.smtpPort = String(res.email.smtpPort);
              this.form.smtpEnableSsl = res.email.smtpEnableSsl;
              this.form.smtpUseDefaultCredentials = res.email.smtpUseDefaultCredentials;
              this.form.smtpDomain = String(res.email.smtpDomain);
              this.form.smtpUserName = String(res.email.smtpUserName);
              this.form.smtpPassword = String(res.email.smtpPassword);
              this.form.testEmailSettingsHeader = String(res.email.defaultFromAddress);
            });
          });
      },
      /**
       * 选择时区
       */
      selectedTimeZoneChange(data: string) {
        this.hostSettings.general.timezone = data;
      },
      /**
       * 选择版本
       */
      versionHandleChange(value: string) {
        this.hostSettings.tenantManagement.defaultEditionId = value;
      },
      /**
       * 宿主用户登陆图片验证码类型
       */
      useCaptchaOnUserLoginHandleChange(value: ValidateCodeType) {
        this.hostSettings.userManagement.captchaConfig.configCaptchaOnUserType = value;
      },
      /**
       * 租户注册图片验证码类型
       */
      CaptchaOnTenantRegistrationTypeChange(value: string) {
        this.hostSettings.tenantManagement.configCaptchaOnTenantType = value;
      },
      /**
       * 强制修改密码时间单位选择
       */
      updatePasswordForceChange(value: TimeUnitEnum) {
        this.hostSettings.security.updatePasswordForceEditDto.timeUnitEnum = value;
      },
      /**
       * 保存全部
       */
      handleSubmit(e) {
        if (
          this.hostSettings.tenantManagement.configCaptchaOnTenantLength == null ||
          this.hostSettings.userManagement.captchaConfig.configCaptchaOnUserLength == null ||
          (this.hostSettings.security.updatePasswordForceEditDto.switchStatus == true &&
            this.hostSettings.security.updatePasswordForceEditDto.effectiveTimeLast == null) ||
          this.hostSettings.security.passwordComplexity.requiredLength == null ||
          this.hostSettings.security.defaultPasswordComplexity.requiredLength == null ||
          this.hostSettings.security.userLockOut.maxFailedAccessAttemptsBeforeLockout == null ||
          this.hostSettings.security.userLockOut.defaultAccountLockoutSeconds == null
        ) {
          this.notify.warn(this.l('Thelengthrangecannotbeempty'));
          return;
        }
        e.preventDefault();
        (this.$refs.formRef as any).validate().then(() => {
          Object.assign(this.hostSettings.email, this.form);
          this.loading = true;
          this.hostSettingsServiceProxy
            .updateAllSettings(this.hostSettings as any)
            .finally(() => {
              this.loading = false;
            })
            .then(() => {
              this.notify.success(this.l('SavedSuccessfully'));
              this.getAllSetting();
              AppPreBootstrap.getUserConfiguration(() => {});
            });
        });
      },
      /**
       * 发送测试邮箱
       */
      sendTestEmail() {
        this.loading = true;
        this.setEmailInput.emailAddress = this.form.testEmailSettingsHeader;
        this.hostSettingsServiceProxy
          .sendTestEmail(this.setEmailInput)
          .finally(() => {
            this.loading = false;
          })
          .then(() => {
            this.notify.success(this.l('TestEmailSentSuccessfully'));
          });
      },
    },
  });
</script>

<style scoped lang="less">
  :deep(.requiredlabel) {
    display: inline-block;
    margin-right: 4px;
    color: #ff4d4f;
    font-size: 14px;
    font-family: SimSun, sans-serif;
    line-height: 1;
    content: '*';
  }
  :deep(.ant-form-item-label) {
    text-align: left;
  }
  :deep(.ant-input-group-addon) {
    padding: 0 !important;
  }
  :deep(.ant-input) {
    height: 35px;
  }
  :deep(.text-grey-dark) {
    color: #ccc;
    font-size: 13px;
  }
</style>
